package com.dyz.leetcode;

import java.util.ArrayList;

public class IsPalindrome234 {
    //递归， 时间超时
    public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null){return true;}
        ListNode pre=head, curr=head;
        while (curr.next!=null){
            pre=curr;
            curr=curr.next;
        }
        if(head.val!=curr.val){return false;}
        pre.next = null;
        return isPalindrome(head.next);
    }

    public boolean isPalindrome1(ListNode head) {
        //数组
        ArrayList<Integer> list = new ArrayList<>();

        ListNode curr = head;

        while (curr!=null){
            list.add(curr.val);
            curr = curr.next;
        }
        int start =0;
        int end = list.size()-1;
        while (start<=end){
            if(!list.get(start).equals(list.get(end))){return false;}
            start++;
            end--;
        }
        return true;
    }

    //快慢指针
    public boolean isPalindrome2(ListNode head) {
        if(head==null||head.next==null){return true;}
        ListNode fast=head, slow=head, pre=null;
        //快慢指针定位中间点
        while (fast!=null&&fast.next!=null){
            fast = fast.next.next;
            pre = slow;
            slow = slow.next;
        }

        //技术和偶数的问题
        if(fast==null){
            //odd numbers of nodes
            pre.next=null;
            slow=reverse(slow);

            while (head!=null){
                if(head.val!=slow.val){return false;}
                head=head.next;
                slow=slow.next;
            }
        }else {
            pre.next=null;
            ListNode next = slow.next;
            slow.next= null;
            slow = reverse(next);

            while (head!=null){
                if(head.val!=slow.val){return false;}
                head=head.next;
                slow=slow.next;
            }
        }
        return true;


    }
    private ListNode reverse(ListNode head){
        ListNode pre=null;

        while (head!=null){
            ListNode next = head.next;
            head.next = pre;
            pre=head;
            head=next;
        }
        return pre;
    }
}
